package org.hd.onlineexcel.controller;

import cn.dev33.satoken.util.SaResult;
import org.hd.onlineexcel.service.OnlineOfficeService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/onlineOffice/")
public class OnlineOfficeController {


    @Resource
    OnlineOfficeService onlineOfficeService;

    @PostMapping("getData")
    public SaResult getOnlineData(
            @RequestBody String gridKey,
            HttpServletResponse response
    ) throws IOException {


        String data = onlineOfficeService.getData();

        if(data != null){
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Length", "" + data.getBytes().length);

            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(data.getBytes());
            outputStream.flush();
            outputStream.close();
            return null;
        }
        return new SaResult(500,"查询失败",null);
    }

    @PostMapping("saveData")
    public SaResult saveData(
            @RequestBody Map<String,String> map
    ){
        boolean flag = onlineOfficeService.saveData(map.get("excelOption"));
        if(flag){
            return new SaResult(200,"保存成功",null);
        }
        return SaResult.error("保存失败");
    }


}
